<?php
namespace App\Logic\calculate;

use Illuminate\Support\Facades\Cache;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\DB;

class Level
{
    public static function index($info,$cny,$capacity)
    {

        $path = rtrim($info->path,',');
        $path = ltrim($path,0);
        $path = ltrim($path,',');
        $arr = explode(',',$path);
        array_push($arr,$info->id);
        $arr = array_reverse($arr);
        $count = count($arr);
        if($count>0){

            DB::table('user')->whereIn('id',$arr)->increment('performance',$cny);
            DB::table('user')->whereIn('id',$arr)->increment('capacity',$capacity);

            for($i=0;$i<$count;$i++){
                $direct = Db::table('user')->where('pid',$arr[$i])->select('capacity')->get()->toArray();
                $direct_arr = array_column($direct,'capacity');
                if(!$direct_arr){
                    continue;
                }
                $max = max($direct_arr);
                $total = 0;
                foreach($direct_arr as $k=>$v){
                    $total +=$v;
                }
                $little_performance = $total - $max;
                $level = self::get_level($little_performance);
                $user_level = Db::table('user')->where('id',$arr[$i])->value('level');
                $user_level_lock = Db::table('user')->where('id',$arr[$i])->value('level_lock');
                if($level != $user_level and $user_level_lock == 0){
                    Db::table('user')->where('id',$arr[$i])->update(['level'=>$level]);
                }
            }
        }

    }


    public static function get_level($performance){
        $config_level = Cache::get('config_level');
        $level_arr = array_column($config_level,'capacity');
        if(in_array($performance,$level_arr)){
            $key = array_keys($level_arr,$performance)[0];
        }else{
            array_push($level_arr,$performance);
            sort($level_arr);
            $key = array_keys($level_arr,$performance)[0]-1;
        }
        $level = $config_level[$key]->level;
        return $level;
    }
}





